package cn.alone.order.service.impl;

import cn.alone.basic.constant.BaseConstants;
import cn.alone.basic.service.impl.BaseServiceImpl;
import cn.alone.basic.util.CodeGenerateUtils;
import cn.alone.basic.util.QuartzJobInfo;
import cn.alone.order.domain.OrderAddress;
import cn.alone.order.domain.ProductOrder;
import cn.alone.order.mapper.OrderAddressMapper;
import cn.alone.order.mapper.ProductOrderMapper;
import cn.alone.order.service.IProductOrderService;
import cn.alone.pay.domain.PayBill;
import cn.alone.pay.mapper.PayBillMapper;
import cn.alone.pay.service.IPayBillService;
import cn.alone.product.domain.Product;
import cn.alone.product.service.IProductService;
import cn.alone.user.domain.Logininfo;
import cn.alone.user.domain.User;
import cn.alone.user.domain.UserAddress;
import cn.alone.user.mapper.UserAddressMapper;
import cn.alone.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private IProductService productService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;

    @Override
    public String submit(Map<String, Object> params, Logininfo currentLogininfo) {
        Long serviceMethod = Long.valueOf(params.get("service_method").toString());
        /*收件地址*/
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        /*订单id*/
        Long productId = Long.valueOf(params.get("product_id").toString());
        /*订单*/
        Product product = productService.loadById(productId);
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        /*保存用户订单地址*/
        UserAddress address = userAddressMapper.loadById(addressId);
        /*赋值*/
        ProductOrder productOrder = initProductOrder(product, user);
        /*生成唯一支付标识*/
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        productOrder.setPaySn(paySn);
        /*返回自增id*/
        productOrderMapper.save(productOrder);
        OrderAddress orderAddress = initOrderAddress(productOrder, address);
        orderAddressMapper.save(orderAddress);
        /*生成支付单并支付*/
        PayBill bill = initPayBillOrder(payMethod, user,productOrder);
        payBillMapper.save(bill);
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        /*定时器名称*/
        jobInfo.setJobName(BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT + productOrder.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("type",BaseConstants.PAY_TIMEOUT_CANCEL_PRODUCT);
        map.put("orderId",productOrder.getId());
        /*订单类型和id*/
        jobInfo.setParams(map);
        /*执行时间*/
        jobInfo.setFireDate(productOrder.getLastPayTime());
        return payBillService.pay(bill);
    }

    private OrderAddress initOrderAddress(ProductOrder productOrder, UserAddress address) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(address, orderAddress);
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        return orderAddress;
    }

    private ProductOrder initProductOrder(Product product, User user) {
        ProductOrder productOrder = new ProductOrder();
        productOrder.setDigest("[摘要]对"+product.getName()+"服务订单！");
        /*待支付*/
        productOrder.setState(0);
        /*售价*/
        productOrder.setPrice(product.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        productOrder.setOrderSn(orderSn);
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());
        productOrder.setShop_id(product.getShop_id());
        //最后支付时间
        productOrder.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));
        return productOrder;
    }

    private PayBill initPayBillOrder(Long payMethod, User user, ProductOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]服务"+order.getOrderSn()+"支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        /*0 支付宝 1 微信  2 银联*/
        bill.setPayChannel(payMethod);
        bill.setBusinessType(cn.alone.pay.constants.PayConstants.FUWU_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        /*冗余字段*/
        bill.setNickName(user.getUsername());
        return bill;
    }

   /* @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;
    @Override
    public String submit(Map<String, Object> params, User user) {
        Long addressId = Long.parseLong(params.get("address_id").toString());
        Long productId = Long.parseLong(params.get("product_id").toString());
        Long pay_method = Long.parseLong(params.get("pay_method").toString());
        Product product = productMapper.loadById(productId);
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        System.out.println(userAddress);
        //1创建订单
        //1.1 创建订单
        ProductOrder productOrder = getProductOrder(params,userAddress,product,user);
        productOrderMapper.save(productOrder);
        //1.2 保存关联表 orderAdress productOrderDetail

        System.out.println(productOrder.getId());
        OrderAddress orderAddress = userAddress2orderAddress(userAddress);
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        orderAddressMapper.save(orderAddress);

        ProductOrderDetail productOrderDetail = product2productOrderDetail(product);
        productOrderDetail.setOrder_id(productOrder.getId());
        productOrderDetailMapper.save(productOrderDetail);

        // 2 创建支付单
        PayBill payBill = order2PayBill(pay_method, productOrder, user);
        payBillMapper.save(payBill);

        // 3 订单倒计时取消处理
        QuartzJobInfo info = new QuartzJobInfo();
        info.setType(JobTypeConsts.WAIT_PRODUCT_ORDER_PAY_CANCEL_JOB);
        String jobName = "ProductOrderCancelJob"+productOrder.getId();
        Map<String, Object> infoParams = new HashMap<>();
        infoParams.put("orderId",productOrder.getId());
        Date fireDate = productOrder.getLastPayTime();
        info.setJobName(jobName);
        info.setParams(infoParams);
        info.setFireDate(fireDate);
        quartzService.addJob(info);
        // 4 跳转到支付页面,通过调用支付接口，要把这个数据返回前台，前台处理后跳转支付宝支付页面
        String payData = payBillService.pay(payBill);
        return payData;
    }

    @Override
    public void cancelOrder(Long orderId) {
        ProductOrder productOrder = productOrderMapper.loadById(orderId);
        if(productOrder.getState()!=-1){
            productOrder.setState(-1);
            productOrderMapper.update(productOrder);
        }

        String paySn = productOrder.getPaySn();
        PayBill payBill = payBillMapper.loadByUnionPaySn(paySn);
        if (payBill.getState()!=-1){
            payBill.setState(-1);
            payBillMapper.update(payBill);
        }

    }

    private PayBill order2PayBill(Long pay_method, ProductOrder productOrder,User user) {
        PayBill payBill = new PayBill();
        payBill.setDigest(productOrder.getDigest());
        payBill.setMoney(productOrder.getPrice());
        payBill.setUnionPaySn(productOrder.getPaySn());
        payBill.setState(0);
        payBill.setLastPayTime(productOrder.getLastPayTime());
        payBill.setPayChannel(pay_method);
        payBill.setBusinessType(PayConstants.BUSINESSTYPE_PRODUCT);
        payBill.setBusinessKey(productOrder.getId());
        payBill.setCreateTime(new Date());
        payBill.setUser_id(productOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(productOrder.getShop_id());
        return payBill;
    }

    private ProductOrderDetail product2productOrderDetail(Product product) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,productOrderDetail);
        return productOrderDetail;
    }

    private OrderAddress userAddress2orderAddress(UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setContacts(userAddress.getContacts());
        return orderAddress;
    }

    @Autowired
    private ShopMapper shopMapper;
    private ProductOrder getProductOrder(Map<String, Object> params,UserAddress userAddress,Product product, User user) {
        Long productNum = Long.parseLong(params.get("product_num").toString());
        ProductOrder productOrder = new ProductOrder();

        productOrder.setDigest("[服务订单]购买"+productNum+"次"+product.getName()+"服务！");
        productOrder.setState(0);
        BigDecimal price  = product.getSaleprice().multiply(new BigDecimal(100))
                .multiply(new BigDecimal(productNum));
        productOrder.setPrice(price);
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        Date lastPayTime = new Date(System.currentTimeMillis()+60*1000); //当前时间+30分钟
        productOrder.setLastPayTime(lastPayTime);
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.loadAll());
        productOrder.setShop_id(nearestShop.getId());
        productOrder.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        return productOrder;
    }*/

}
